﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using DeviceCommon;
using ComLib.ComType;
using LogLib;
using System.Timers;
using Newtonsoft.Json;
using System.IO;

namespace IDCardReader
{
    public class SDTReader : DeviceBase
    {
        /// <summary>
        /// 阅读器连接的串口号（或者USB接口索引）
        /// </summary>
        protected int _iPort = 0;
        public int iPort
        {
            get { return _iPort; }
        }

        private Polling poll = null;

        protected readonly string strZPPath = @"D:\\zp.bmp";

        /// <summary>
        /// 阅读器选项
        /// </summary>
        protected IDCReaderOption _option = new IDCReaderOption();
        public IDCReaderOption Option
        {
            get { return _option; }
            set { _option = value; }
        }

        private SDT_IDCardReader _reader = new SDT_IDCardReader();

        public SDTReader()
        {
            LoadConfig();
        }

        private void LoadConfig()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        protected override void OnWorkingCompleted(string outParams)
        {
            base.OnWorkingCompleted(outParams);
        }

        protected override void OnWorkingFailed(string message)
        {
            base.OnWorkingFailed(message);
        }

        public bool OpenPort(int port)
        {
            if (_reader.TryOpen(port))
            {
                _bExited = false;
                _bInited = true;
                string strlog = string.Format("阅读器初始化成功, 串口号:{0}.", _reader.PortNo);
                Log.WriteAsync(strlog);
            }
            else
            {
                _error = string.Format("阅读器初始化失败。\n{0}", _reader.ErrorMessage);
                Log.WriteAsync(_error);
            }
            return _bInited;
        }

        public bool Close()
        {
            try
            {
                _reader.Exit();
                _bExited = true;
                _state = DeviceState.NotInitialized;
                DeleteZP();
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
            }
            finally
            {
                _bInited = false;
            }
            return _bExited;
        }

        public override void Init(string param, out string outParam)
        {
            outParam = "";
            if (_bInited)
            {
                return;
            }
            if (_reader.Init())
            {
                _bInited = true;
                string strlog = string.Format("阅读器初始化成功, 串口号:{0}.", _reader.PortNo);
                Log.WriteAsync(strlog);
            }
            else
            {
                _error = string.Format("阅读器初始化失败。\n{0}", _reader.ErrorMessage);
                Log.WriteAsync(_error);
            }
        }

        public override bool DoAction(string param, out string outParam)
        {
            return Read(param, out outParam);
        }

        public override void Start(string param, out string outParam)
        {
            outParam = null;
            poll = new Polling(Read, param);
            poll.TimeoutMilliSecond = TimeoutMillisecond;
            poll.ScanInterval = _option.ScanInterval;
            poll.DoFailed += this.OnDoFailed;
            poll.Timeout += this.OnDoTimeout;
            poll.Start(OnWorkingCompleted);
        }

        public override void Stop(string param, out string outParam)
        {
            outParam = null;
            if (poll != null)
            {
                poll.Stop();
                poll.Dispose();
                poll = null;
            }
        }

        public override void Exit(string inParams, out string outParam)
        {
            outParam = "";
            try
            {
                _reader.Exit();
                _bExited = true;
                _state = DeviceState.NotInitialized;
                DeleteZP();
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
            }
            finally
            {
                _bInited = false;
            }
        }

        /// <summary>
        /// 清理身份证头像相片
        /// </summary>
        public void DeleteZP()
        {
            try
            {
                if (!File.Exists(strZPPath))
                {
                    File.Delete(strZPPath);
                }
            }
            catch (Exception ex)
            {
                string strLog = string.Format("删除ZP发生了异常: {0}", ex.ToString());
                Log.WriteExceptionAsync(strLog);
            }
        }

        public bool ReadCard(out IDCardAll info)
        {
            info = null;
            bool readSuccess = false;
            try
            {
                readSuccess = _reader.ReadCardInfo(false);
                if (readSuccess)
                {
                    info = ConvertTo(_reader.m_CardInf);                  
                }
                else
                {
                    _error = _reader.ErrorMessage;
                }
                return readSuccess;
            }
            catch (Exception ex)
            {
                _error = string.Format("读取身份证信息发生了异常.\n异常详情:{0}", ex.ToString());
                Log.WriteExceptionAsync(_error);
                return false;
            }
        }

        /// <summary>
        /// 执行单次读取身份证操作
        /// </summary>
        /// <returns></returns>
        public bool Read(string inParams, out string outParams)
        {
            outParams = "";
            _error = "";
            if (!_bInited)
            {
                _error = "阅读器未初始化.";
                return false;
            }
            bool readSuccess = false;
            try
            {
                readSuccess = _reader.ReadCardInfo(false);
                if (readSuccess)
                {
                    outParams = GetCardInfoString(ref _reader.m_CardInf);
                }
                else
                {
                    _error = _reader.ErrorMessage;
                }
                return readSuccess;
            }
            catch (Exception ex)
            {
                _error = string.Format("读取身份证信息发生了异常.\n异常详情:{0}", ex.ToString());
                Log.WriteExceptionAsync(_error);
                return false;
            }
        }

        private IDCardAll ConvertTo(IDCardInfo cardInfo)
        {
            IDCardAll info = new IDCardAll();
            info.address = cardInfo.m_IDadd;
            info.sex = cardInfo.m_IDsex;
            info.birthday = cardInfo.m_IDborn;
            info.signdate = cardInfo.m_IDdepartment;
            info.number = cardInfo.m_IDCARDNO;
            info.name = cardInfo.m_IDname;
            info.people = cardInfo.m_IDnation;
            string dateStr = cardInfo.m_IDdate;
            int index = dateStr.IndexOf('-');
            if (index >= 0)
            {
                info.validtermOfStart = dateStr.Substring(0, index);
                int length = dateStr.Length - index - 1;
                info.validtermOfEnd = dateStr.Substring(index + 1, length);
            }
            info.HeadImage = cardInfo.m_BmpFilePathName;
            return info;
        }

        private string GetCardInfoString(ref IDCardInfo cardInfo)
        {
            IDCardAll info = new IDCardAll();
            info.address = cardInfo.m_IDadd;
            info.sex = cardInfo.m_IDsex;
            info.birthday = cardInfo.m_IDborn;
            info.signdate = cardInfo.m_IDdepartment;
            info.number = cardInfo.m_IDCARDNO;
            info.name = cardInfo.m_IDname;
            info.people = cardInfo.m_IDnation;
            string dateStr = cardInfo.m_IDdate;
            int index = dateStr.IndexOf('-');
            if (index >= 0)
            {
                info.validtermOfStart = dateStr.Substring(0, index);
                int length = dateStr.Length - index - 1;
                info.validtermOfEnd = dateStr.Substring(index + 1, length);
            }
            info.HeadImage = cardInfo.m_BmpFilePathName;
            return JsonConvert.SerializeObject(info);
        }

        /// <summary>
        /// 显示设备的选项配置对话框
        /// </summary>
        /// <param name="inParam"></param>
        public override void ShowConfigDialog(string inParam)
        {
            FormSetting form = new FormSetting();
            form.ShowDialog();
        }
    }
}
